package com.njupt.towerssystem.controller;

import com.njupt.towerssystem.domain.Managers;
import com.njupt.towerssystem.services.LoginManagerService;
import com.njupt.towerssystem.services.PowersService;
import com.njupt.towerssystem.services.RegisterManagerService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/sys")
@CrossOrigin("*")
public class ManagersCtrl {
    @Resource
    private LoginManagerService managersService;
    @Resource
    private RegisterManagerService registerManagerService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private PowersService powersService;

    @RequestMapping("/reg")
    public String reg(Managers mi) {
        boolean ret = registerManagerService.regManager(mi);
        //响应实例（字符串拼接）
        //Object m = stringRedisTemplate.opsForHash().get("managers", mi.getLoginname() + "," + mi.getLoginpwd());
        if(ret) {
            return "{\"userreg\":\"success\"}";
        }else{
            return "{\"userreg\":\"fail\"}";
        }
    }

    @RequestMapping("/login")
    public Managers login(
            @RequestParam(required = false, name = "loginname") String loginname,
            @RequestParam(required = false, name = "loginpwd") String loginpwd,
            @RequestParam(required = false, name = "token") String token
    ) {
        return managersService.login(loginname,loginpwd,token);
    }


    @RequestMapping("/setpower")
    public String setuserpower(
            @RequestParam(required = false,name = "ruid") int ruid,
            @RequestParam(required = false,name = "userid")int userid,
            @RequestParam(required = false,name = "powerid")int powerid,
            @RequestParam(required = false,name = "isgrant")String isgrant){
        if(isgrant.equalsIgnoreCase("y")){
            powersService.grantRule(ruid,powerid,userid);
        }else{
            powersService.revokeRule(powerid,userid);
        }
        return "{\"powerset\":\"success\"}";
    }

    @RequestMapping("/insertpower")
    public String regpower(
            @RequestParam(required = false,name = "ruleid") int ruleid,
            @RequestParam(required = false,name = "rulename") String rulename){
        if(rulename==null){return "0";}
        powersService.addNewRule(ruleid,rulename);
        return "{\"powersreg\":\"success\"}";
    }
}